package com.x.compute.common.function;

import cn.hutool.core.date.*;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 日期中月份偏移函数
 * 函数示例：DATEMONTH(date, offset)
 * @author xuxin
 */
public class DateMonthFunction extends AbstractFunction {

    @Override
    public String getName() {
        return "DATEMONTH";
    }

    /**
     * 函数处理逻辑
     * @param env 变量上下文
     * @param arg1 日期字符串，格式 yyyy-MM-dd
     * @param arg2 日期偏移量，支持浮点数
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        String date = FunctionUtils.getStringValue(arg1, env);
        DateTime dateTime = DateTime.of(date, DatePattern.NORM_DATE_PATTERN);
        String offset = arg2.getValue(env).toString();
        BigDecimal offsetNumber = new BigDecimal(offset).setScale(2, BigDecimal.ROUND_HALF_UP);
        int offsetMonth = offsetNumber.setScale(0,BigDecimal.ROUND_DOWN).intValue();
        dateTime = DateUtil.offsetMonth(dateTime,offsetMonth);
        int offsetDays = offsetNumber.remainder(BigDecimal.ONE).multiply(new BigDecimal(30)).setScale(0, BigDecimal.ROUND_UP).intValue();
        dateTime = DateUtil.offsetDay(dateTime,offsetDays);
        return new AviatorString(dateTime.toString(DatePattern.NORM_DATE_PATTERN));
    }

}
